

window.para = {
    TRACK:'utm_source=EDM&utm_medium=',
    rev : '',
    domain:'',
    number:1,
    date:20171021,
    tmp : $("<div id='model'></div>"),
    html:null,
    head:'',
    //me系统
    meSystem:['orderplus','calladream','fashionmia','fashionme','berrylook','popreal','comfybub'],
    //云站
    cloud:[
        'cathybuy','selaros','onlyyo','omnifever','trendysuper','sebellamore','lacielara','callabuy','stylemoco','bellalike',
        'maxinina','youkime','allsukey','elegayou','charmmiss','mixpia','dreesinew'
    ],
    //shopify系统站点
    shopify:[
        'aqilabuy','lululike',
        'stylishplus','mumetaz','hellocloth','binkish',
        'lukalula','chicgostyle','maxpassion','lolabuy',
        'pinksia','swankmyway','pipidress','chicsia','chicdb',
        'sherop','chicloco','fashionbestway','myladystar','nanachicway',
        'wakalula','wikichic','youthkiss','hahacloth','missiapick',
        'rolachic','tammyrita','dressinyou','maggiemood','stylevivian','stylishmolly',
        'vavaspace','fofoshoes','starryou','dressliving','kindafavor','charrcter','eguapo',
        'vellishy','yoyosfashion','yoyocloth','holapick','wowmia','shedig','gracylady','feverway',
        'mybesthoney','whiteseek','gracyme','chicmay','mikidress','topjara','calakitty','wakasia','chicsit','elladr',
        'bioopo','wikiyoung','vinavince','arealook','colabingo','peekkabo','chicokay','cedarjoy','ecogora','knightmaker',
        'cupstime','mrcovic','buzzyly','yatacity'
    ],
    api:{ //下标参数 1.当前模板追踪 2.请求接口 3.图片资源阿里云前缀 4.当前币种符号
        'bellalike-spain':['BL','https://shop.bellalike.com/admin/index.php?route=api/product/infoapi&lan=MXN&goods_sn=','',true],
        'luvyle':['LV','https://www.luvyle.com/admin/index.php?route=api/product/infoapi&goods_sn='],
        'cicilookshop':['COP','https://www.cicilookshop.com/admin/index.php?route=api/product/infoapi&goods_sn=',''],

        'fashionme':['FME','https://websolr.fashionme.com/dla?insku=','fm.'],
        'berrylook':['BERRY','https://websolr.berrylook.com/dla?insku=','bl.'],
        'calladream': ['CDR', 'https://websolr.calladream.com/dla?insku=', 'cd.'],
        'popreal': ['POP', 'https://websolr.popreal.com/dla?insku=', 'pr.'],
        'orderplus':['ORPL','https://websolr.stylishplus.com/dla?site=17&insku=',''],
        'fashionmia':['FM','http://websolr.fashionmia.com/dla?flashtrue=1&insku=','mia.'],
        'comfybub':['CUB','http://mses.orderplus.com/dla?site=20&insku=',''],

        //云站
        'cathybuy':['CUY','http://cloud-api.orderplus.com/api/goods/list?siteId=218&spu=',''],
        'selaros':['SOS','http://cloud-api.orderplus.com/api/goods/list?siteId=167&spu=',''],
        'onlyyo':['OYO','http://cloud-api.orderplus.com/api/goods/list?siteId=244&spu=',''],
        'omnifever':['OER','http://cloud-api.orderplus.com/api/goods/list?siteId=426&spu=',''],
        'trendysuper':['TER','http://cloud-api.orderplus.com/api/goods/list?siteId=425&spu=',''],
        'sebellamore':['SRE','http://cloud-api.orderplus.com/api/goods/list?siteId=543&spu=',''],
        'lacielara':['LRA','http://cloud-api.orderplus.com/api/goods/list?siteId=561&spu=',''],
        'callabuy':['CUY','http://cloud-api.orderplus.com/api/goods/list?siteId=177&spu='],
        'stylemoco':['SCO','http://cloud-api.orderplus.com/api/goods/list?siteId=856&spu='],
        'bellalike':['BL','http://cloud-api.orderplus.com/api/goods/list?siteId=858&spu='],
        'maxinina':['MNA','http://cloud-api.orderplus.com/api/goods/list?siteId=966&spu='],
        'youkime':['YME','http://cloud-api.orderplus.com/api/goods/list?siteId=898&spu='],
        'allsukey':['AEY','http://cloud-api.orderplus.com/api/goods/list?siteId=1018&spu='],
        'elegayou':['EOU','http://cloud-api.orderplus.com/api/goods/list?siteId=946&spu='],
        'charmmiss':['CSS','http://cloud-api.orderplus.com/api/goods/list?siteId=540&spu='],
        'mixpia':['MIA','http://cloud-api.orderplus.com/api/goods/list?siteId=1020&spu='],
        'dreesinew':['DEW','http://cloud-api.orderplus.com/api/goods/list?siteId=1331&spu='],

        //'bellalike':['BL','http://api-pms.orderplus.com/api/product/edm?pid=46&spus='],
        'aqilabuy':['AQB','http://api-pms.orderplus.com/api/product/edm?pid=6&spus=',''],
        'lululike':['LLK','http://api-pms.orderplus.com/api/product/edm?pid=9&spus=',''],
        'stylishplus':['STPL','http://api-pms.orderplus.com/api/product/edm?pid=41&spus=',''],
        'mumetaz':['MMT','http://api-pms.orderplus.com/api/product/edm?pid=12&spus=',''],
        'hellocloth':['HCH','http://api-pms.orderplus.com/api/product/edm?pid=42&spus=',''],
        'binkish':['BSH','http://api-pms.orderplus.com/api/product/edm?pid=54&spus=',''],
        'lukalula':['LLA','http://api-pms.orderplus.com/api/product/edm?pid=49&spus=',''],
        'chicgostyle':['CHSE','http://api-pms.orderplus.com/api/product/edm?pid=50&spus=',''],
        'maxpassion':['MAXN','http://api-pms.orderplus.com/api/product/edm?pid=10&spus=',''],
        'lolabuy':['LOL','http://api-pms.orderplus.com/api/product/edm?pid=15&spus=',''],
        'pinksia':['PKA','http://api-pms.orderplus.com/api/product/edm?pid=18&spus=',''],
        'swankmyway':['smyay','http://api-pms.orderplus.com/api/product/edm?pid=60&spus=',''],
        'pipidress':['PIPI','http://api-pms.orderplus.com/api/product/edm?pid=73&spus=',''],
        'chicsia':['CCA','http://api-pms.orderplus.com/api/product/edm?pid=77&spus=',''],
        'chicdb':['CDB','http://api-pms.orderplus.com/api/product/edm?pid=61&spus=',''],
        'sherop':['SHP','http://api-pms.orderplus.com/api/product/edm?pid=89&spus=',''],
        'chicloco':['CCO','http://api-pms.orderplus.com/api/product/edm?pid=83&spus=',''],
        'fashionbestway':['FAY','http://api-pms.orderplus.com/api/product/edm?pid=66&spus=',''],
        'myladystar':['MAR','http://api-pms.orderplus.com/api/product/edm?pid=62&spus=',''],
        'nanachicway':['NAY','http://api-pms.orderplus.com/api/product/edm?pid=97&spus=',''],
        'wakalula':['WLA','http://api-pms.orderplus.com/api/product/edm?pid=78&spus=',''],
        'wikichic':['WIC','http://api-pms.orderplus.com/api/product/edm?pid=82&spus=',''],
        'youthkiss':['YSS','http://api-pms.orderplus.com/api/product/edm?pid=96&spus=',''],
        'hahacloth':['HTH','http://api-pms.orderplus.com/api/product/edm?pid=92&spus=',''],
        'missiapick':['MCK','http://api-pms.orderplus.com/api/product/edm?pid=100&spus=',''],
        'rolachic':['RIC','http://api-pms.orderplus.com/api/product/edm?pid=81&spus=',''],
        'tammyrita':['TTA','http://api-pms.orderplus.com/api/product/edm?pid=87&spus=',''],
        'dressinyou':['DOU','http://api-pms.orderplus.com/api/product/edm?pid=93&spus=',''],
        'maggiemood':['MOD','http://api-pms.orderplus.com/api/product/edm?pid=122&spus=',''],
        'stylevivian':['SAN','http://api-pms.orderplus.com/api/product/edm?pid=136&spus=',''],
        'stylishmolly':['SLY','http://api-pms.orderplus.com/api/product/edm?pid=115&spus=',''],
        'vavaspace':['VCE','http://api-pms.orderplus.com/api/product/edm?pid=88&spus=',''],
        'fofoshoes':['FES','http://api-pms.orderplus.com/api/product/edm?pid=86&spus=',''],
        'starryou':['SOU','http://api-pms.orderplus.com/api/product/edm?pid=69&spus=',''],
        'dressliving':['DNG','http://api-pms.orderplus.com/api/product/edm?pid=51&spus=',''],
        'kindafavor':['KOR','http://api-pms.orderplus.com/api/product/edm?pid=125&spus=',''],
        'charrcter':['CER','http://api-pms.orderplus.com/api/product/edm?pid=131&spus=',''],
        'eguapo':['EPO','http://api-pms.orderplus.com/api/product/edm?pid=169&spus=',''],
        'vellishy':['VHY','http://api-pms.orderplus.com/api/product/edm?pid=170&spus=',''],
        'yoyosfashion':['YON','http://api-pms.orderplus.com/api/product/edm?pid=128&spus=',''],
        'yoyocloth':['YTH','http://api-pms.orderplus.com/api/product/edm?pid=130&spus=',''],
        'holapick':['HCK','http://api-pms.orderplus.com/api/product/edm?pid=99&spus=',''],
        'wowmia':['WIA','http://api-pms.orderplus.com/api/product/edm?pid=84&spus=',''],
        'shedig':['SIG','http://api-pms.orderplus.com/api/product/edm?pid=94&spus=',''],
        'gracylady':['GDY','http://api-pms.orderplus.com/api/product/edm?pid=174&spus=',''],
        'feverway':['FAY','http://api-pms.orderplus.com/api/product/edm?pid=240&spus=',''],
        'mybesthoney':['MEY','http://api-pms.orderplus.com/api/product/edm?pid=67&spus=',''],
        'whiteseek':['WEK','http://api-pms.orderplus.com/api/product/edm?pid=139&spus=',''],
        'gracyme':['GME','http://api-pms.orderplus.com/api/product/edm?pid=367&spus=',''],
        'chicmay':['CAY','http://api-pms.orderplus.com/api/product/edm?pid=114&spus=',''],
        'mikidress':['MSS','http://api-pms.orderplus.com/api/product/edm?pid=178&spus=',''],
        'topjara':['TRA','http://api-pms.orderplus.com/api/product/edm?pid=132&spus=',''],
        'mikidress':['MSS','http://api-pms.orderplus.com/api/product/edm?pid=178&spus=',''],
        'topjara':['TRA','http://api-pms.orderplus.com/api/product/edm?pid=132&spus=',''],
        'calakitty':['CTY','http://api-pms.orderplus.com/api/product/edm?pid=192&spus=',''],
        'wakasia':['WIA','http://api-pms.orderplus.com/api/product/edm?pid=79&spus=',''],
        'chicsit':['CIT','http://api-pms.orderplus.com/api/product/edm?pid=117&spus=',''],
        'elladr':['EDR','http://api-pms.orderplus.com/api/product/edm?pid=161&spus=',''],
        'bioopo':['BPO','http://api-pms.orderplus.com/api/product/edm?pid=269&spus=',''],
        'wikiyoung':['WNG','http://api-pms.orderplus.com/api/product/edm?pid=135&spus=',''],
        'vinavince':['VCE','http://api-pms.orderplus.com/api/product/edm?pid=460&spus=',''],
        'arealook':['AOK','http://api-pms.orderplus.com/api/product/edm?pid=671&spus=',''],
        'colabingo':['CGO','http://api-pms.orderplus.com/api/product/edm?pid=338&spus=',''],
        'peekkabo':['PBO','http://api-pms.orderplus.com/api/product/edm?pid=190&spus=',''],
        'chicokay':['CAY','http://api-pms.orderplus.com/api/product/edm?pid=108&spus=',''],
        'cedarjoy':['COY','http://api-pms.orderplus.com/api/product/edm?pid=352&spus=',''],
        'ecogora':['ERA','http://api-pms.orderplus.com/api/product/edm?pid=145&spus=',''],
        'knightmaker':['KER','http://api-pms.orderplus.com/api/product/edm?pid=480&spus=',''],
        'cupstime':['CME','http://api-pms.orderplus.com/api/product/edm?pid=463&spus=',''],
        'mrcovic':['MIC','http://api-pms.orderplus.com/api/product/edm?pid=186&spus=',''],
        'buzzyly':['BLY','http://api-pms.orderplus.com/api/product/edm?pid=255&spus='],
        'yatacity':['YTY','http://api-pms.orderplus.com/api/product/edm?pid=777&spus=']
    },
    banner:null,
    block1:null,
    block2:null,
    block3:null,
    block4:null,
    list1:[],
    list2:[],
    list3:[],
    col:{},
    renderReady:{
        list1:false,
        list2:false,
        list3:false
    },
    errData:{
        list1:{},
        list2:{},
        list3:{},
        errNum:0
    },
    siteInfo:null,
    labelInfo:null,
    navInfo:null
};

inEvent();

function inEvent(){

    //初始化local里的数据
    initData();
    //初始化组件
    //$('#selectRev').comSelect();
    //保存
    $('#save').on('click',function(){
        result(1)
    });
    //重置
    $('#reset').on('click',function(){
        localStorage.removeItem('templateData');
    });
    //上传事件
    $("input[type='file']").on('change',function(){
        up($(this)[0],$(this).attr('data-name'))
    });

    //选择模板事件
    $("input[name='template']").on('change',function(){

        para.rev = $(this).val();
        //根据模板选择list跳转路径
        var domainBase = para.rev.replace(/([a-zA-Z]+)-*.*/,'$1');
        var s = para.rev == 'fashionmia' ? '':'s';
        if(para.meSystem.indexOf(para.rev) >= 0){//en
            para.domain = 'http'+s+'://www.' + domainBase + '.com/Products/';
        }else if(para.cloud.indexOf(para.rev) >= 0){
            para.domain = 'https'+'://www.' + domainBase + '.com/item/';
        }else{
            para.domain = 'https://www.' + domainBase + '.com/';
        }
        //拼接追踪
        para.api[para.rev][0] = para.TRACK + para.api[para.rev][0];

        para.tmp.load('template/mark/base'+'.html?'+new Date().getTime()+' #M',function(res,status){
            if(status == 'success'){
                var str = res;
                para.head = str.replace(/<table\s+id[\s\S]+<\/html>/g,'');
                $.comMessage({
                    type:'success',
                    text:para.rev + '模板载入完成',
                    time:2500
                })
            }
        })
    });

    //生成
    $('#start').on('click',function(){
        //执行基本校验
        if(!para.rev){
            $.comMessage({
                type:'warning',
                text:'请选择模板！',
                time:2500
            });
            return;
        }
        //para赋值
        result();

        //如果未填写sku数据就直接渲染(否则先请求sku)
        if(para.list1.length == 0 &&  para.list2.length == 0 && para.list3.length == 0){
            renderAll();
        }else{
            for(var i=1;i<=3;i++){
                if(para['list'+i].length < 1){
                    para.renderReady['list'+i] = true;
                }else{
                    request(para['list'+i],i);
                }
            }
        }

    });

    renderListSite();
}

//请求所有SKU数据列表
function request(arr,type){
    var num = 0;
    //var errBox = [];
    var arrObj = [];

    //var isTrue = new RegExp(para.rev,"g").test(para.shopify);
    var isTrue = para.shopify.indexOf(para.rev) >= 0;

    arr.forEach(function(item,index){
        $.ajax({
            type:'get',
            url:para.api[para.rev][1] + item,
            data:'',
            dataType:isTrue ? 'json': 'jsonp',
            jsonp:isTrue ? false:'jsonpcallback',
            beforeSend:function(req){
                isTrue ? req.setRequestHeader('pms-token','orderplus') : '';
                $('#start').prop('disabled',true)
            },
            success:function(data){
                var obj = null;
                if(typeof data == 'string'){data = JSON.parse(data)}
                if(para.meSystem.indexOf(para.rev) >= 0){
                    obj = data.response.data[0]
                }else if(para.cloud.indexOf(para.rev) >= 0){
                    obj = data.data.list[0];
                }else if(isTrue){
                    obj = data.response[0];
                }else{
                    obj =  data.data
                }
                if(!obj){
                    para.errData['list'+type][index] = true;
                }else{
                    arrObj[index] = obj;
                }
            },
            error:function(xhr,err,msg){
                //errBox.push(item);
                para.errNum += 1;
                para.errData['list'+type][index] = true;
            },
            complete:function(){
                num++;
                if(num>=arr.length){
                    var newData = dataStructure(arrObj);
                        renderList(newData,type);
                        para.renderReady['list'+type] = true;
                        //如果当前所填写的所有SKU列表数据请求完成
                    if(renderReady()){
                        var err1 = Object.keys(para.errData.list1).length;
                        var err2 = Object.keys(para.errData.list2).length;
                        var err3 = Object.keys(para.errData.list3).length;
                        if(err1>0 || err2>0 || err3>0){
                            $.alert('sku'+(err1+err2+err3)+'条没有数据是否继续?',function(){
                                renderAll();
                                //重置页面sku覆盖
                                /*var resetList1 = para.list1.filter(function(item,index){
                                    if(!para.errData['list' + type][index]){
                                        return item;
                                    }
                                });
                                para.list1 = resetList1;
                                $("textarea[name='list1-sku']").val(resetList1.join(','));
                                */
                                for(var i=1;i<=3;i++){
                                    var resetList = para['list'+i].filter(function(item,index){
                                        if(!para.errData['list'+i][index]){
                                            return item;
                                        }
                                    });
                                    para['list'+i] = resetList;
                                    $("textarea[name='list"+i+"-sku']").val(resetList.join(','));
                                }
                            })
                        }else{
                            renderAll();
                        }
                        $('#start').prop('disabled',false);
                    }

                }
            }
        })
    })
}
function renderAll(){
    renderBanner();
    editFill();
    dateReplace();
    para.html = para.head + para.tmp.html() + "</body></html>";
    para.html = para.html.replace(/&amp;/g,'&').replace(/SITENAME/g,para.rev);
    $.comMessage({
        type:'prompt',
        text:'模板渲染完成！',
        time:2500
    });
    saveHtml();
}

//渲染banner/view
function renderBanner(){
    var navBanner = para.tmp.find("[data-name='banner']");
    var count = 1000;
    var labelCount = 1100;
    var navCount = 700;
    //banner
    var blink = para.banner.link.indexOf('?')>=0 ? '&'+para.api[para.rev][0]:'?'+para.api[para.rev][0];

    navBanner.find('a').prop('href',para.banner.link+blink+para.date+'&utm_campaign=Link508');
    navBanner.find('img').prop({
        //'src': link + "banner1.jpg",
        'src': para.banner.src,
        'title':para.banner.title,
        'alt':para.banner.title
    });


    //logo
    para.tmp.find("[data-name='logo']").prop('src',para.logo.link).css('height',para.logo.height + 'px');
    para.tmp.find("[data-name='logoLink']").prop('href',"https://www."+para.rev+".com/?"+para.api[para.rev][0]+para.date+'&utm_campaign=Link508');
    //view-more
    para.tmp.find("[data-name='more']").prop({
        'href':para.banner.link+blink+para.date+'&utm_campaign=Link509',
        'title':para.banner.title
    });

    /*left-title*/
    para.tmp.find("[data-name='title']").text(para.title);

    /*列表title*/
    para.tmp.find(".listTitle").each(function(index,item){
        var _this = $(item);
        var name = _this.attr('data-name');
        if(para.col[name]){
            _this.text(para.col[name]).show();
        }else{
            _this.hide();
        }
    });

    /**
     ** 区块渲染
     **/
    for(var i=1;i<=4;i++){
        bannerCol(i);
        setSiteInfo(i);
        setLabelInfo(i);
        setNavInfo(i)
    }
    function bannerCol(n){
        var col = $("input[name=b"+n+"Num]").val();
        if(para['block' + n].length>0){
            //var col = $("input[name='b1Num']");
            var blockTmp = para.tmp.find("#modelB").clone();
            var str = '';
            $.each(para['block'+ n],function(index,item){
                if(index == col){return false;}
                var sign = item.link.indexOf('?')>=0 ? '&'+para.api[para.rev][0] : '?'+para.api[para.rev][0];
                blockTmp.find('a').prop('href',item.link+sign+para.date+'&utm_campaign=Link' + count);
                blockTmp.find('img').prop({
                    'src':item.src,
                    'title':item.title,
                    'alt':item.title
                });
                count++;
                str+= blockTmp.html()
            });
            para.tmp.find("#block" + n).append(str);
        }
    }

    /**
     ** 导航信息渲染
     **/
    function setNavInfo(n){
        var name = para.navInfo[n-1].name;
        var link =  para.navInfo[n-1].link;
        var sign = link.indexOf('?')>=0 ? '&'+para.api[para.rev][0] : '?'+para.api[para.rev][0];
        para.tmp.find("[data-name='nav-name-"+n+"']").prop({
            'href':link + sign + para.date + '&utm_campaign=Link' + navCount,
            'title':name
        }).html(name);
        navCount++;
    }

    /**
     ** 站点信息渲染
     **/
    function setSiteInfo(n){
        var name = para.siteInfo[n-1].name;
        var link =  para.siteInfo[n-1].link;
        para.tmp.find("[data-name='site-name-"+n+"']").prop('href',link).html(name);
    }

    /**
     ** label导航渲染
     **/
    function setLabelInfo(n){
        var name = para.labelInfo[n-1].name;
        var link =  para.labelInfo[n-1].link;
        var sign = link.indexOf('?')>=0 ? '&'+para.api[para.rev][0] : '?'+para.api[para.rev][0];
        para.tmp.find("[data-name='label-link-"+n+"']").prop('href',link + sign + para.date + '&utm_campaign=Link' + labelCount );
        para.tmp.find("[data-name='label-name-"+n+"']").html(name);
        labelCount++;
    }


    //隐藏显示
    //if(!para.dress.src||!para.hot.src){para.tmp.find(".dress-hot").hide();}
    //if(!para.banner2.src){navBanner2.hide();}
}

//渲染链接
function dateReplace(){
    para.tmp.find('.d').each(function(index,item){
        var str = $(item).prop('href');
        if(/utm_source/.test(str)){
            var link = str.replace(/utm_source.+[A-Z]+\d+/,para.api[para.rev][0] + para.date);
            $(item).prop('href',link);
        }
    })
}

//数据结构处理
function dataStructure(res){
    var arr = [];

    /*{goods_name:'',url:'',img:'',price:'',market_price:''};*/
    $.each(res,function(index,item){
        if(!item){
            return true;
        }
        var tmpUrl = '';
        var obj = {};
        /**
         ** me系统
         **/
        if(para.meSystem.indexOf(para.rev) >= 0){
            //名称
            obj.goods_name = item.goods_name;
            //链接
            tmpUrl = item.goods_name.replace(/^\s+/,'').replace(/\s{2,}/g,' ').replace(/\&*/g,'');
            obj.url = para.domain + tmpUrl.toLowerCase().split(' ').join('-') + '-' + item.id + '.html?';
            //图片
            var rep = para.rev == 'fashionmia' ? 'g-':'';
            var sizePara = "";
                if(para.rev == 'calladream'){
                    sizePara = "@!h250-w250"
                }else if(para.rev == 'popreal'){
                    sizePara = "@!h320-w320"
                }else{
                    sizePara = "@!"+rep+"h400-w300";
                }

            obj.img = "http://"+para.api[para.rev][2]+"aopcdn.com/" + item.main_original_img_path.replace(/^images/,'goods') + sizePara;

        }else if(para.cloud.indexOf(para.rev) >= 0){
            /**
             ** cloud
             **/
            obj.goods_name = item.name;
            tmpUrl = item.name.replace(/^\s+/,'').replace(/\s{2,}/g,' ').replace(/\&*/g,'');
            obj.url = para.domain + tmpUrl.toLowerCase().split(' ').join('-') + '-' + item.id + '.html?';
            obj.img = item.mainImg + '@!w420-h560';

        }else if(para.shopify.indexOf(para.rev) >= 0){
            /**
             ** AQB
             **/
            obj.goods_name = item.name;
            obj.url = item.link + '?';
            obj.url = obj.url.replace(new RegExp("(^http.+com)*"),para.domain.replace(/\/$/,''));
            obj.img = item.img;

        }else{
            /**
             ** open
             **/

            //名称
            obj.goods_name = item.goods_name;
            //链接
            tmpUrl = item.goods_name.replace(/^\s+/,'').replace(/\s{2,}/g,' ');
            obj.url = para.domain + tmpUrl.toLowerCase().split(' ').join('-') + '-p-' + item.goods_id  + '.html?';
            //图片
            obj.img = item.thumb_pic_detail[0].img_path;
        }

        //价格
        if(para.cloud.indexOf(para.rev) >= 0){
            obj.price = para.api[para.rev][3] ? item.salePrice : '$' + item.salePrice.toFixed(2);
        }else{
            obj.price = para.api[para.rev][3] ? item.price : '$' + item.price.toFixed(2);
        }
        //划线价
        if(item.marketPrice && item.activityId ){
            obj.market_price = para.api[para.rev][3] ? item.marketPrice : '$' + item.marketPrice.toFixed(2);
        }else if(item.market_price){
            obj.market_price = para.api[para.rev][3] ? item.market_price : '$' + item.market_price.toFixed(2);
        }else if(item.before_price){
            obj.market_price = para.api[para.rev][3] ? item.before_price : '$' + item.before_price.toFixed(2);
        }else{
            obj.market_price = 0;
        }

        arr.push(obj);
    });
    return arr;
}

//渲染列表
function renderList(data,n){
    var str = '';
    var arrDom = [];
    var modelA = para.tmp.find("#modelA").clone();
    //一排多少个
    var col = para.col['list'+n+'Num'];
    var colNum = (function(){
        if(col == 2){
            return '50%';
        }else if(col == 3){
            return '33.333%';
        }else{
            return '25%';
        }
    })();

    data.forEach(function(item,index){
        if(!item){
            $.comMessage({
                type:'prompt',
                text:'sku不存在！',
                time:2500
            });
            return;
        }
        modelA.find("[data-name='link']").prop({
            'href':item.url+para.api[para.rev][0]+para.date+'&utm_campaign=Link' + para.number,
            'title':para.api[para.rev][3] ? item.title_en : item.goods_name
        });
        para.number++;
        modelA.find("[data-name='link2']")
            .prop('href',item.url+para.api[para.rev][0]+para.date+'&utm_campaign=Link' + para.number);
        para.number++;

        //如果有描述
        if(modelA.find("[data-name='link3']").length){
            modelA.find("[data-name='link3']").prop({
                'href':item.url+para.api[para.rev][0]+para.date+'&utm_campaign=Link' + para.number,
                'title':para.api[para.rev][3] ? item.title_en : item.goods_name
            }).html(para.api[para.rev][3] ? item.title_en : item.goods_name);
            para.number++;
        }

        //如果有划线价则添加否则清除划线价
        if(modelA.find("[data-name='market_price']").length && item.market_price){
            modelA.find("[data-name='market_price']").html(item.market_price);
        }else{
            modelA.find("[data-name='market_price']").html("");
        }
        modelA.find("[data-name='img']").prop({
            'src':item.img,
            'alt':item.goods_name
        });
        modelA.find("[data-name='price']").html( item.price );

        //如果不是第一个则调整间距
        /*if((index%col) == 0){
            modelA.find('td').css('padding-left','0px');
        }else{
            modelA.find('td').css('padding-left','10px');
        }*/
        modelA.find('td').css('width',colNum);
        arrDom.push(modelA.children('tr').html())
    });

    //console.log(arrDom)
    arrDom.forEach(function(item,index){
        if(index%col == 0){
            item = "<tr>" + item
        }else if(index%col == (col-1)){
            item = item + "</tr>"
        }
        str+=item;
    });

    para.tmp.find("#tbody"+ n).html(str);
}

//para赋值操作
function result(type){
    var date = $("input[name='date']").val();
    var title = $("input[name='title']").val();
    //banner信息获取
    var banner = {
        link : $("input[name='bannerLink']").val(),
        src : $("input[name='bannerSrc']").val(),
        title : $("input[name='bannerTitle']").val()
    };

    //logo信息
    var logo = {
        link:$("input[name='logo-link']").val(),
        height:$("input[name='logo-height']").val(),
    };

    //底部label导航获取
    var navInfo = [];
    function getNavInfo(n){
        var name = $("input[name=nav-name-"+n+"]").val();
        var link = $("input[name=nav-link-"+n+"]").val();
        var navObj = {
            name:name,
            link:link
        };
        navInfo.push(navObj);
    }

    //底部站点信息获取
    var siteInfo = [];
    function getSiteInfo(n){
        var name = $("input[name=site-name-"+n+"]").val();
        var link = $("input[name=site-link-"+n+"]").val();
        var siteObj = {
            name:name,
            link:link
        };
        siteInfo.push(siteObj);
    }

    //底部label导航获取
    var labelInfo = [];
    function getLabelInfo(n){
        var name = $("input[name=label-name-"+n+"]").val();
        var link = $("input[name=label-link-"+n+"]").val();
        var labelObj = {
            name:name,
            link:link
        };
        labelInfo.push(labelObj);
    }

    var block1 = [],block2 = [],block3 = [],block4 = [];
    for(var i=1;i<=4;i++){
        getSiteInfo(i);
        getLabelInfo(i);
        getNavInfo(i);
        for(var j=1;j<=3;j++){
            var obj = {
                link:$("input[name='b"+i+"-link-"+j+"']").val(),
                title:$("input[name='b"+i+"-title-"+j+"']").val(),
                src:$("input[name='b"+i+"-src-"+j+"']").val()
            };
            switch(i){
                case 1:
                    block1.push(obj);
                    break;
                case 2:
                    block2.push(obj);
                    break;
                case 3:
                    block3.push(obj);
                    break;
                case 4:
                    block4.push(obj);
                    break;
            }
        }
    }

    //sku
    var list1 = $("textarea[name='list1-sku']").val().replace(/\s/g,'');
    var list2 = $("textarea[name='list2-sku']").val().replace(/\s/g,'');
    var list3 = $("textarea[name='list3-sku']").val().replace(/\s/g,'');

    //分栏
    var list1Num = $("input[name='list1-num']").val();
    var list2Num = $("input[name='list2-num']").val();
    var list3Num = $("input[name='list3-num']").val();
    var b1Num= $("input[name='b1Num']").val();
    var b2Num = $("input[name='b2Num']").val();
    var b3Num = $("input[name='b3Num']").val();
    var b4Num = $("input[name='b4Num']").val();
    var col = {
        list1Num : list1Num,
        list2Num : list2Num,
        list3Num : list3Num,
        list1Title : $("input[name='list1-title']").val(),
        list2Title : $("input[name='list2-title']").val(),
        list3Title : $("input[name='list3-title']").val(),
        b1Num : b1Num,
        b2Num : b2Num,
        b3Num : b3Num,
        b4Num : b4Num
    };

    //是获取还是存储本地
    if(!type){
        para.date = date;
        para.title = title;
        para.banner = banner;
        para.block1 = block1;
        para.block2 = block2;
        para.block3 = block3;
        para.block4 = block4;
        para.list1 = list1 ? list1.split(',') : [];
        para.list2 = list2 ? list2.split(',') : [];
        para.list3 = list3 ? list3.split(',') : [];
  /*      para.list1Title = list1Title;
        para.list2Title = list2Title;*/
        para.col = col;
        para.siteInfo = siteInfo;
        para.labelInfo = labelInfo;
        para.navInfo = navInfo;
        para.logo = logo;
    }else{
        var jsonData = {
            date:date,
            title:title,
            banner:banner,
            block1:block1,
            block2:block2,
            block3:block3,
            block4:block4,
            list1:list1,
            list2:list2,
            list3:list3,
           /* list1Title:list1Title,
            list2Title:list2Title,*/
            col:col,
            siteInfo:siteInfo,
            labelInfo:labelInfo,
            navInfo:navInfo,
            logo:logo
        };
        localStorage.templateData = JSON.stringify(jsonData);
    }
}

//初始化local里的数据
function initData(){

    var jsonData = localStorage.templateData ? JSON.parse(localStorage.templateData) : {};
    $("input[name='date']").val(jsonData.date);
    $("input[name='title']").val(jsonData.title);
    $("textarea[name='list1-sku']").val(jsonData.list1);
    $("textarea[name='list2-sku']").val(jsonData.list2);
    $("textarea[name='list3-sku']").val(jsonData.list3);
    if(jsonData.logo){
        $("input[name='logo-link']").val(jsonData.logo.link);
        $("input[name='logo-height']").val(jsonData.logo.height);
    }
    if(jsonData.banner){
        $("input[name='bannerLink']").val(jsonData.banner.link);
        $("input[name='bannerSrc']").val(jsonData.banner.src);
        $("input[name='bannerTitle']").val(jsonData.banner.title);
    }
    if(jsonData.col){
        $("input[name='list1-num']").val(jsonData.col.list1Num);
        $("input[name='list2-num']").val(jsonData.col.list2Num);
        $("input[name='list3-num']").val(jsonData.col.list3Num);
        $("input[name='list1-title']").val(jsonData.col.list1Title);
        $("input[name='list2-title']").val(jsonData.col.list2Title);
        $("input[name='list3-title']").val(jsonData.col.list3Title);
        $("input[name='b1Num']").val(jsonData.col.b1Num);
        $("input[name='b2Num']").val(jsonData.col.b2Num);
        $("input[name='b3Num']").val(jsonData.col.b3Num);
        $("input[name='b4Num']").val(jsonData.col.b4Num);
    }
    for(var i=1;i<=4;i++){
        $("#block" + i).find(".box-list").each(function(index,item){
            fill(jsonData,$(this),index,item)
        });
        //导航信息/填充站点信息/填充label信息
        fillInfo(i,jsonData)
    }
}

//填充站点
function fillInfo(n,data){
    var siteInfo = data.siteInfo;
    var labelInfo = data.labelInfo;
    var navInfo = data.navInfo;
    if(siteInfo){
        $("input[name='site-name-"+n+"']").val(siteInfo[n-1].name);
        $("input[name='site-link-"+n+"']").val(siteInfo[n-1].link);
    }
    if(labelInfo){
        $("input[name='label-name-"+n+"']").val(labelInfo[n-1].name);
        $("input[name='label-link-"+n+"']").val(labelInfo[n-1].link);
    }
    if(navInfo){
        $("input[name='nav-name-"+n+"']").val(navInfo[n-1].name);
        $("input[name='nav-link-"+n+"']").val(navInfo[n-1].link);
    }
}


//图片上传
function up(inputObj,name){
    var fd = new FormData();
    fd.append('file',inputObj.files[0]);
    fd.append("site_name",para.rev);
    $.ajax({
        type : 'post',
        url : 'http://admin.fashionmia.net/opbm.php?a=EdmImages&m=Api',
        data : fd,
        cache : false,
        dataType:'json',
        processData : false,
        contentType : false,
        success : function(data){
            if(data.status == 0){
                //debugger;
                $("input[name='"+name+"']").val(data.data.img);
            }
        },
        error : function(){
            $.comMessage({
                type:'warning',
                text:'图片上传失败！',
                time:2500
            });
        }
    })
}

//保存html
function saveHtml(){
    $.ajax({
        type : 'post',
        url : 'http://admin.fashionmia.net/opbm.php?a=EdmHtml&m=Api',
        data:{
            html:para.html,
            site_name:para.rev
        },
        success:function(res){
            var data = JSON.parse(res);
            if(data.status == 0){
                $("input[name='callback']").val(data.data.img);
                $.comMessage({
                    type:'prompt',
                    text:'链接已生成！',
                    time:2500
                });
            }
        },
        error : function(){
            $.comMessage({
                type:'prompt',
                text:'模板保存失败！',
                time:2500
            });
        },
        complete:function(){
            $('#start').prop('disabled',false)
        }
    })
}

//填充数据
function fill(data,_this,index,item){
    var jsonData = data;
    var text = _this.parent('section').prop('id');
    $(item).find('.form-content').children('input').each(function(indexChild,itemChild){
        var str = '';
        switch(indexChild){
            case 0:
                str = 'link';
                break;
            case 1:
                str = 'title';
                break;
            case 2:
                str = 'src';
                break;
        }
        if(jsonData[text]){
            $(itemChild).val(jsonData[text][index][str]);
        }
    })
}
//是否全部请求完毕
function renderReady(){
    var isTrue = true;
    $.each(para.renderReady,function(index,item){
        if(!item){isTrue = false;return false;}
    });
    return isTrue;
}

//渲染站点
function renderListSite(){
    var str = "";
    $.each(window.para.api,function(index,item){
        str+='<li data-val="'+index+'" class="sel-list">'+index+'</li>';
    })
    $("#selectTemplate").find('.sel-content').html(str);
}
//编辑器
function editFill(){
    var str =  p.quill.container.firstChild.innerHTML;
    var isTrue = p.editSwitch.checked().isTrue;
    if(isTrue && (p.quill.getLength()>1)){
        para.tmp.find("#edit-box").html(str);
        para.tmp.find(".view-more").closest("tr").remove();
    }else{
        para.tmp.find("#edit-box").remove();
    }
}